//
//  BTEUrlToolsManager.swift
//  BTE
//
//  Created by Mike Zhang on 2025/8/26.
//

import UIKit

final class BTEUrlToolsManager {

    static let shared = BTEUrlToolsManager()

    func handleURL(_ urlString: String, in viewController: UIViewController?, model: Any?) {
        guard let url = URL(string: urlString) else { return }

        switch url.scheme?.lowercased() {
        case "http", "https":
            openWebURL(url, in: viewController)

        case "ivo":
            handleCustomScheme(url, in: viewController, model: model)
        default:
            break
        }
    }

    // MARK: - HTTP/HTTPS Handler

    private func openWebURL(_ url: URL, in viewController: UIViewController?) {
        guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return }

        // 添加公共参数
        let additionalParams = urlInfo().map { URLQueryItem(name: $0.key, value: $0.value) }
        components.queryItems = (components.queryItems ?? []) + additionalParams

        guard let finalURL = components.url else { return }

        let webVC = BTEWebViewViewController(url: finalURL.absoluteString)
        viewController?.navigationController?.pushViewController(webVC, animated: true)
    }

    // MARK: - Custom Scheme Handler

    private func handleCustomScheme(_ url: URL, in viewController: UIViewController?, model: Any?) {
        guard url.host == "coth.VUP.arn" else { return }

        switch url.path {
        case "/porkin":
            let settingsVC = BTESettingViewController()
            settingsVC.model = model as? BTEMEModel
            viewController?.navigationController?.pushViewController(settingsVC, animated: true)
            break
        case "/amotus":
            if let productId = url.queryParameters["privileger"] {
                let productVC = BTEProductViewController()
                productVC.pid = productId
                viewController?.navigationController?.pushViewController(productVC, animated: true)
            }
            break
        default:
            break
        }
    }

    // MARK: - Public Parameters Builder

     func urlInfo() -> [String: String] {
        var info: [String: String] = [:]
        if let sessionID = UserDefaults.standard.string(forKey: USER_TOKEN), !sessionID.isEmpty {
            info["upbows"] = sessionID
        }
        
        info["unpernicious"] = BTELanguageManager.shared.currentLanguage == .YINDU ? "1" : "2"
        info["defalcations"] = UIDevice.current.types.rawValue
        info["prescinded"] = "1.0.0"
        info["seminationalistic"] = UIDevice.current.systemVersion
        info["valylene"] = BTEDeviceIdentifierManager.shared.advertisingID()
        info["began"] = BTEDeviceIdentifierManager.shared.vendorID()
    
        return info
    }
}

